package com.etcsoft.pagedesigner.common.log;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.PropertyConfigurator;

import com.etcsoft.pagedesigner.PageDesignerPlugin;

/**
 * @author korman21@gmail.com
 *
 */
public class LoggerFactory {
    private static boolean isConfigured;
    @SuppressWarnings("rawtypes")
    private static Map<Class, ILogger> loggersRepository;
    private static final String LOG4J_FILENAME = "log4j.properties";

    @SuppressWarnings("rawtypes")
    public static ILogger getLogger(Class clazz) {
        configure();
        if (loggersRepository.containsKey(clazz)) {
            return loggersRepository.get(clazz);
        } else {
            ILogger slf4jLogger = new Slf4jLogger(org.slf4j.LoggerFactory.getLogger(clazz));
            loggersRepository.put(clazz, slf4jLogger);
            return slf4jLogger;
        }
    }

    @SuppressWarnings("rawtypes")
    private synchronized static void configure() {
        if (isConfigured) {
            return;
        }
        isConfigured = true;
        // initialize MAP (cache)
        loggersRepository = new HashMap<Class, ILogger>();
        // configure logger
        File file = new File("configuration", LOG4J_FILENAME);
        if (file.exists()) {
            PropertyConfigurator.configure(file.getAbsolutePath());
        } else {
            // configure from default: local resources
            URL entry = PageDesignerPlugin.getDefault().getBundle().getEntry(LOG4J_FILENAME);
            PropertyConfigurator.configure(entry);
        }
    }
}
